package com.dabao.controller.admin;

import com.dabao.bean.Phone;
import com.dabao.controller.BaseController;
import com.dabao.query.Page;
import com.dabao.query.PhoneQuery;
import com.dabao.service.PhoneService;
import com.dabao.service.SearchService;
import com.dabao.service.impl.RedisService;
import com.dabao.util.KeyConstant;
import com.dabao.util.web.ResponseUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by card on 2016/5/29.
 */
@Controller
@RequestMapping("/admin/phone")
public class PhoneController extends BaseController {

    @Autowired
    private PhoneService phoneService;

    @Autowired
    private SearchService searchService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("")
    public String index() {
        return "/admin/phone/list";
    }

    @RequestMapping("/list")
    @ResponseBody
    public String list(@RequestParam(value = "draw", required = false, defaultValue = "1")String draw,
                       @RequestParam(value = "start", required = false, defaultValue = "0") int pageNo,
                       @RequestParam(value = "length", required = false, defaultValue = "0") int pageSize,
                       @RequestParam(value = "phone", required = false) String phone) {

        PhoneQuery query = new PhoneQuery();
        query.setPhone(phone);
        query.setOrderColumn("id");
        query.setIsDesc(1);
        query.setPage(Page.getPage(pageNo, pageSize));

        int total = phoneService.selectCount(query);
        List<Phone> roles = phoneService.selectList(query);
        return ResponseUtils.listData(total, roles, draw);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file")MultipartFile file,
                         @RequestParam(value = "callback")String callback) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = bufferedReader.readLine();
            int count = 0;
            long currentTimeMillis = System.currentTimeMillis();
            while (StringUtils.isNotBlank(line)) {
                redisService.rpush(String.valueOf(currentTimeMillis), line);
                count++;
                line = bufferedReader.readLine();
            }
            redisService.hset(KeyConstant.KEY_MAP, String.valueOf(currentTimeMillis), String.valueOf(count));
        } catch (Exception e) {
            logger.error("upload error", e);
        }
        String json = ResponseUtils.success("上传成功");
        return String.format("<script>%s(%s)</script>", callback, json);
    }

    @RequestMapping("/uploadNormal")
    @ResponseBody
    public String uploadNormal(@RequestParam(value = "file")MultipartFile file,
                         @RequestParam(value = "callback")String callback) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = bufferedReader.readLine();
            while (line != null) {
                Phone phone = new Phone();
                phone.setPhone(line);
                phone.setType(0);
                phone.setRemark("");
                searchService.insert(phone);
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            logger.error("upload error", e);
        }
        String json = ResponseUtils.success("上传成功");
        return String.format("<script>%s(%s)</script>", callback, json);
    }

    @RequestMapping("/uploadCrank")
    @ResponseBody
    public String uploadCrank(@RequestParam(value = "file")MultipartFile file,
                         @RequestParam(value = "callback")String callback) {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line = bufferedReader.readLine();
            while (line != null) {
                Phone phone = new Phone();
                phone.setPhone(line);
                phone.setType(1);
                phone.setRemark("骚扰号码");
                searchService.insert(phone);
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            logger.error("upload error", e);
        }
        String json = ResponseUtils.success("上传成功");
        return String.format("<script>%s(%s)</script>", callback, json);
    }

    @RequestMapping("/export")
    public void export(@RequestParam(value = "type")Integer type,
                       HttpServletResponse response) {
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/plain;charset=UTF-8");

        try {
            PhoneQuery query = new PhoneQuery();
            if(type == 0) {
                response.addHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode("正常", "UTF-8")
                                + ".txt");
                query.setType(0);
            }

            else {
                response.addHeader("Content-Disposition",
                        "attachment;filename=" + URLEncoder.encode("骚扰", "UTF-8")
                                + ".txt");
                query.setType(1);
            }

            List<Phone> phones = phoneService.selectList(query);
            for(Phone phone : phones) {
                response.getWriter().write(String.format("%s|%s\r\n", phone.getPhone(), phone.getRemark()));
            }
            response.getWriter().flush();
        } catch (Exception e) {
            logger.error("export error", e);
        }
    }
}
